package com.gx.auth.service;

import com.gx.auth.dao.RoleDAO;
import com.gx.auth.dao.RoleFunctionDAO;
import com.gx.auth.entity.Role;
import com.gx.auth.entity.RoleFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * Created by Administrator on 2017/4/4.
 */
@Service
public class RoleService {
    @Autowired
    private RoleDAO roleDAO;
    @Autowired
    private RoleFunctionDAO roleFunctionDAO;

    /**保存角色信息  同时保存角色对应的功能信息
     * 根据角色 添加功能
     * @param role 角色
     * @param roleFunctions 角色对应的功能
     */
    public void addRole(Role role , Collection<RoleFunction> roleFunctions){
        roleDAO.insertRole(role);
        roleFunctions.forEach((rf)->{
            rf.setRoleId(role.getId());
        });
        roleFunctionDAO.insertRoleFunctions(roleFunctions);
    }

    /**
     * 修改角色信息 同时修改角色对应的功能
     * @param role
     * @param roleFunctions
     */
    @Transactional
    public void editRole(Role role,Collection<RoleFunction>roleFunctions){
        roleDAO.updateRole(role);
        //关联关系删除
        roleFunctionDAO.deleteByRoleId(role.getId());
        roleFunctions.forEach((rf)->rf.setRoleId(role.getId()));
        roleFunctionDAO.insertRoleFunctions(roleFunctions);
    }
    /**
     *  根据id删除角色
     * @param roleld
     */
    public void deleteRole (Long roleld){
        roleDAO.deleteRole(roleld);
        roleFunctionDAO.deleteByRoleId(roleld);
    }

    /**
     * 分页查询角色信息
     * @param page
     * @param size
     * @return
     */
    public List<Role> getRoles(int page ,int size){
        List<Role> roles = roleDAO.selectRoles(page,size);
        roles.forEach( (role) -> {
            List<RoleFunction> roleFunctions = roleFunctionDAO.findRoleFunctionByRoleId(role.getId());
            StringBuilder functionIds = new StringBuilder();
            roleFunctions.forEach((rf)->{
                functionIds.append(rf.getFunctionId()).append(",");
            });
            if (functionIds.length()>1){
                role.setFunctionIds(functionIds.deleteCharAt(functionIds.length()-1).toString());
            }
        });
        return roles;
    }

    /**
     * 根据ID查询角色信息
     * @param ids 角色ID集合
     * @return
     */
    public List<Role> getRoles (Collection<Long> ids){
        return roleDAO.selectRoles(ids);
    }

    /**
     * 根据用户id 查询用户功能的对应关系
     * @param roleId
     * @return
     */
    public List<RoleFunction> getRoleFunctions(Long roleId){
        return roleFunctionDAO.findRoleFunctionByRoleId(roleId);
    }


}
